package com.littlepay.kr4.paulin.dfeba77.adapter;

import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.littlepay.kr4.paulin.dfeba77.R;
import com.littlepay.kr4.paulin.dfeba77.entity.Sticker;
import com.littlepay.kr4.paulin.dfeba77.fragment.RecyclerViewFragment;
import com.littlepay.kr4.paulin.dfeba77.support.RippleForegroundListener;
import com.littlepay.kr4.paulin.dfeba77.utils.DateUtil;
import com.littlepay.kr4.paulin.dfeba77.utils.SpannableStringUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by florentchampigny on 24/04/15.
 * modify by 77dfeba
 * it contain HeadStickRecycleView
 * getItemCount --> getItemViewType --> onBindViewHolder
 */
public class TestRecyclerViewAdapter extends RecyclerView.Adapter<TestRecyclerViewAdapter.ListViewHolder> {

    private Context mContext;
    //新增的item内容
    //public String[] datas = new String[RecyclerViewFragment.ITEM_COUNT];
    public List<Sticker> data =  new ArrayList<>();
    private List<Integer>  headPosition = new ArrayList<>();
    private static final int TYPE_HEADER = 0;
    private static final int TYPE_CELL = 1;
    private static final int TYPE_FOOT = 2;
    int index = 0;
    int position_indext = 0;//用于循环往复判断HEAD的位置
    public TestRecyclerViewAdapter(Context context,List<Sticker> stickers) {
        if(stickers != null){
            this.data = stickers;
            //第一个数据的长度放进去
            //headPosition.add()
        }
        this.mContext = context;
    }

    @Override
    public int getItemViewType(int position) {
        if(position == 0){
            return TYPE_HEADER;
        }else if(position == data.size()){
            return TYPE_FOOT;
        }else{
                for(int i = 0;i < headPosition.size();i++){
                    if(position == headPosition.get(i)){
                        return TYPE_HEADER;
                    }
                }
                return TYPE_CELL;
            }

    }

    @Override
    public int getItemCount() {
        if(data == null || data.size() == 0){
            return 0;
        } else{
            return data.size() + 1;//加一是为了添加footView
        }
    }

    @Override
    public ListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view;
        switch (viewType) {
            case TYPE_HEADER: {
                view = View.inflate(mContext, R.layout.list_item_card_small_head, null);
                return new ListViewHolder(view);
            }
            case TYPE_CELL: {
                view = View.inflate(mContext, R.layout.list_item_card_small, null);
                return new ListViewHolder(view);
            }
            case TYPE_FOOT:{
                view = View.inflate(mContext, R.layout.list_item_foot, null);
                return new ListViewHolder(view);
            }
        }
        return null;
    }

    @Override
    public void onBindViewHolder(ListViewHolder holder, int position) {
        Sticker sticker;
        //让最新加入的数据展示在最上面,并且最后位置的FOOT没有数据不需要viewHolder
        if(position < data.size()){
            sticker = data.get(data.size()  - position - 1);
            switch (getItemViewType(position)) {
                case TYPE_HEADER:
                    holder.setData(sticker);
                    break;
                case TYPE_CELL:
                    holder.setData(sticker);
                    break;
//                case TYPE_FOOT:
//                    break;
            }
        }
        //lastDate = data.get(position).date;
    }
    /* item内部元素的内部类
    * 包含：
    * 价格
    * 属性（用于显示右侧图标）
    * 日期（用于头部显示）
    * */
    class ListViewHolder extends RecyclerView.ViewHolder {
        //private ImageView imgIcn;
        private TextView price;
        private TextView attri;
        private TextView date;
        private ImageView icon;
        private CardView cardView;
        ListViewHolder(View itemView) {
            super(itemView);
            price = (TextView) itemView.findViewById(R.id.scard_price);
            attri = (TextView) itemView.findViewById(R.id.scard_attri);
            date = (TextView) itemView.findViewById(R.id.tv_sticky_header_view);
            icon = (ImageView) itemView.findViewById(R.id.scard_pic);
            cardView = (CardView) itemView.findViewById(R.id.card_view);

//            RippleForegroundListener rippleForegroundListener = new RippleForegroundListener();
//            rippleForegroundListener.setCardView(cardView);
//            itemView.setOnTouchListener(rippleForegroundListener);
        }
        //TODO:根据消费的字数自适应字体大小
        void setData(Sticker sticker) {
            //Log.index("tag", "data.icn:" + sticker.cost);
            //对于double存入整数默认.0的处理
            //使用自动适应TextView
            //AutofitHelper.create(price);
            if(isIntegerForDouble(sticker.getCost())){
                price.setText(new SpannableStringUtil().getCostspannableString(String.valueOf((int)Math.ceil(sticker.getCost()))));
            }else{
                price.setText(new SpannableStringUtil().getCostspannableString(String.valueOf(interceptionFordouble(sticker.getCost()))));
            }

            //detail内容加上attri才是最终显示内容
            String detail;
            if((sticker.getAttribution() == 0
                    || sticker.getAttribution() == 1
                    || sticker.getAttribution() == 2
                    || sticker.getAttribution() == 3
                    || sticker.getAttribution() == 4
                    || sticker.getAttribution() == 5)
                    && !Objects.equals(sticker.getDetail(), "") && sticker.getDetail() != null){
                detail = sticker.getDetail();
            }else if(sticker.getAttribution() == 6){
                detail = StickerAdapter.attrToString(sticker.getAttribution()) + " " + sticker.getDetail();
            }
            else {
                detail = StickerAdapter.attrToString(sticker.getAttribution());
            }
            //attri.setText(String.valueOf(StickerAdapter.attrToString(sticker.getAttribution()) + sticker.getDetail()));
            attri.setText(detail);
            //对日期是今日的需要显示成今日
            if(DateUtil.timeToDate(sticker.getDate()).equals(DateUtil.getTodayDate())){
                date.setText("今日");
            }else {
                date.setText(DateUtil.timeToDate(sticker.getDate()));
            }
            //icon的图片资源从sticker适配器类获取
            icon.setImageResource(StickerAdapter.attriToIcon(StickerAdapter.attriToInt(sticker.getAttribution())));
        }

    }

    public void insertOneItem(Sticker sticker){
        //数据添加到位置越靠末尾ID越新，因此最新的应该展示在上面
        data.add(data.size()>0?data.size():0,sticker);
        notifyItemInserted(0);
        notifyItemRangeChanged(0,data.size()+1);
    }
    public void insertMoreItem(List<Sticker> stickerList){
        //放在末尾
        data.addAll(0,stickerList);
        //新的头位置加进去
        addHeadPosition(stickerList);
        //notifyItemInserted(0);
        notifyItemRangeChanged(0,stickerList.size());
        notifyItemRangeInserted(0,stickerList.size());
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RecyclerViewFragment.isLoadingMore = false;
            }
        },1000);
    }
    /*判断double是否是整数并
    * @return 布尔 是否是整数*/
    private boolean isIntegerForDouble(double obj) {
        double eps = 1e-10;  // 精度范围
        return obj-Math.floor(obj) < eps;
    }
    /*判断double是否是整数并
    * * @return 截断2为有效数字后的double
    * 防止15.2取出以后成为15.200000000000000000001*/
    private double interceptionFordouble(double obj){
        DecimalFormat df = new DecimalFormat("#.00");
        return Double.parseDouble(df.format(obj));
    }
    private void addHeadPosition(List<Sticker> stickers){
        int position = 0;
        //每个headPosition都是headposition的位置，因此需要累加
        for(int i=0;i<headPosition.size();i++){
            position += headPosition.get(i);
        }
        //新元素的头位置
        position += stickers.size();
        headPosition.add(position);
    }
}